<template>
  <div>
    <div class="projectDetails">
      <div class="app-container details product-details">
        <el-row :gutter="24">
          <el-col :span="5" class="details-left box-card">
            <el-card style="min-height: 100%">
              <!-- 系统介绍 -->
              <div class="details-left-top details-left-box">
                <div class="top">
                  <div class="top-img">
                    <svg-icon
                      :icon-class="'ht_count'"
                      class="block w-80px h-80px m-auto mb-15px"
                    />
                  </div>
                  <label>{{ contractInfo.contractName }}</label>
                  <p>{{ contractInfo.contractNum }}</p>
                </div>
              </div>
              <div class="details-left-box">
                <div class="title">合同信息</div>
                <ul class="cnt qzbm">
                  <li>
                    <el-icon><Notebook /></el-icon>
                    <label>客户名称</label>
                    <p>
                      {{ contractInfo.customerName }}
                    </p>
                  </li>
                  <li>
                    <el-icon><Notebook /></el-icon>
                    <label>合同金额</label>
                    <p>
                      {{
                        contractInfo.contractSum
                          ? contractInfo.contractSum + '万元'
                          : ''
                      }}
                    </p>
                  </li>
                  <li>
                    <el-icon><Notebook /></el-icon>
                    <label>合同到期时间</label>
                    <p>
                      {{ contractInfo.contractTimeEnd }}
                    </p>
                  </li>
                </ul>
              </div>
              <div class="mt-15px flex justify-center">
                <el-button type="primary" plain @click="showModal = true"
                  >合同材料上传</el-button
                >
              </div>
            </el-card>
          </el-col>
          <el-col :span="19" class="box-card">
            <el-card style="min-height: 100%">
              <div class="px-5 py-15px" style="background-color: #fff">
                <el-tabs v-model="activeTabsName" class="details-right-tabs">
                  <el-tab-pane label="合同信息" name="1">
                    <BaseInfo
                      :epibolyData="epibolyData"
                      :tableData="tableData"
                      :epiboly="epiboly"
                      :renderInfo="renderInfo"
                      :projectId="projectId"
                    ></BaseInfo>
                  </el-tab-pane>
                  <!-- <el-tab-pane label="回款信息" name="2"> </el-tab-pane> -->
                </el-tabs>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-dialog
      title="材料上传"
      v-model="showModal"
      width="500"
      @open="getFiles"
    >
      <el-row>
        <el-col :span="12">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="handleFileChange"
            accept=".rar, .zip, .doc, .docx, .pdf"
            :show-file-list="false"
            :multiple="true"
            :disabled="fileList.length >= 3"
          >
            <el-button type="primary" style="font-size: 14px"
              ><el-icon> <UploadFilled /> </el-icon>上传合同</el-button
            >
            <template #tip>
              <div class="el-upload__tip">单个文件不能超过50MB</div>
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <div class="text-14px mt-10px" style="width: 100%">
        <div v-for="(item, index) in fileList" :key="item.fileId">
          <a style="color: #409eff" :href="item.url">{{ item.origFileName }}</a>
          <el-button text plain @click="delFileName(index)">删除</el-button>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" @click="confirmUpload">确定</el-button>
        <el-button @click="closeModal">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ContractDetails" lang="ts">
import BaseInfo from './module/BaseInfo'
import { useRoute, useRouter } from 'vue-router'
import { reactive, getCurrentInstance, toRefs, ref } from 'vue'
import {
  contractDetails,
  uploadFile,
  delFile,
  contractInfoUpdate
} from '@/api/salesManage/contractManage'
import {
  contract_type,
  business_classification,
  affiliation_industry
} from '@/hooks/dict/contract'
import {
  business_attribute //业务属性
} from '@/hooks/dict/useProject'
import { epiboly_work_type } from '@/hooks/dict/contract'
import useTagsViewStore from '@/store/modules/tagsView'
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
const data = reactive({
  epibolyData: [],
  tableData: [],
  renderInfo: [
    { name: '合同名称', value: '', key: 'contractName' },
    { name: '合同编号', value: '', key: 'contractNum' },
    { name: '合同类别', value: '', key: 'contractType' },
    { name: '合同金额（元）', value: '', key: 'contractSum' },
    { name: '履约保证金（元）', value: '', key: 'pb' },
    { name: '履约保证金是否单独支付', value: '', key: 'pbAlonePay' },
    { name: '合同甲方', value: '', key: 'partyaName' },
    { name: '甲方签约人', value: '', key: 'partyaSig' },
    { name: '合同乙方', value: '', key: 'partybName' },
    { name: '乙方签约人', value: '', key: 'partybSig' },
    { name: '关联订单', value: '', key: 'ordOrderContractDto' },
    { name: '关联项目', value: '', key: 'projectName' },
    { name: '合同时间起', value: '', key: 'contractTimeBegin' },
    { name: '合同时间止', value: '', key: 'contractTimeEnd' },
    { name: '销售人员', value: '', key: 'salesmanName' },
    { name: '签订时间', value: '', key: 'sinTime' },
    { name: '所属产业', value: '', key: 'industry' },
    { name: '业务分类', value: '', key: 'businessClassify' },
    { name: '合同标的内容说明', value: '', key: 'remark' },
    { name: '上传合同', value: '', key: 'fileNames' },
    { name: '合同所需材料', value: '', key: 'accFileList' }
  ]
})

const projectId = ref()
const { epibolyData, tableData, renderInfo } = toRefs(data)

const activeTabsName = ref('1') //激活tab
const rcId = ref(route.query.id) // 合同id
const epiboly = ref(false) // 是否存在人力外包
const contractInfo = ref({}) // 合同信息
const contractDetail = ref()
async function init() {
  const res = await contractDetails(rcId.value)
  epibolyData.value = res.data.ordHroEntity
  epibolyData.value.forEach(v => {
    v.workName = ref(epiboly_work_type).value[Number(v.workType)].label
  })
  tableData.value = res.data.ordProjectCheckEntity
  epiboly.value = res.data.businessType === '1'
  const info = res.data
  contractDetail.value = structuredClone(res.data.accFileList)
  contractInfo.value = {
    contractName: info.contractName,
    contractNum: info.contractNum,
    customerName: info.customerName,
    contractSum: info.contractSum,
    contractTimeEnd: info.contractTimeEnd,
    status: info.status
  }
  projectId.value = res.data.ordProjectId
  renderInfo.value.forEach(v => {
    if (info[v.key]) {
      v.value = info[v.key]
    }
    if (v.key === 'contractType') {
      if (v.value !== '0010') {
        v.value = ref(contract_type).value.filter(
          m => m.value == v.value
        )[0]?.label
      } else {
        v.value = ref(business_attribute).value.filter(
          m => m.value == info['businessType']
        )[0]?.label
      }
    }
    if (v.key === 'pbAlonePay') {
      v.value = info[v.key] === '1' ? '是' : '否'
    }
    // if (v.key === 'ordOrderContractDto') {
    //   v.value = (info[v.key] || [])
    //     .map(v => {
    //       return v.ordName
    //     })
    //     .toString()
    // }
    if (v.key === 'fileNames') {
      v.value = info.sysAttachFiles || []
    }
    if (v.key === 'sinTime') {
      v.value = info[v.key]?.replace(/00:00:00/, '')
    }
    if (v.key === 'industry') {
      v.value = ref(affiliation_industry).value.filter(
        m => m.value == v.value
      )[0]?.label
    }
    if (v.key === 'businessClassify') {
      v.value = ref(business_classification).value.filter(
        m => m.value == v.value
      )[0]?.label
    }
  })
}

// 合同材料上传
const showModal = ref(false)
const fileList = ref([])

function getFiles() {
  fileList.value = contractDetail.value || []
}

function beforeAvatarUpload(rawFile) {
  console.log(rawFile)
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过50MB!')
    return false
  }
  return true
}
// 上传合同
async function handleFileChange(params) {
  const result = beforeAvatarUpload(params.file)
  if (!result) return
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}
// 删除文件
const deleteFileList = ref([])
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      // const file = fileList.value[index]
      const deleteFile = fileList.value.splice(index, 1)
      deleteFileList.value.push(...deleteFile)
      // proxy.$modal.msgSuccess(res.data)
    })
  } catch (error) {
    console.log(error)
  }
}

function confirmUpload() {
  if (fileList.value.length > 3) {
    proxy.$modal.msgError('最多只能上传3个文件')
    return
  }
  if (!fileList.value.length && !deleteFileList.value.length) {
    closeModal()
    return
  }
  contractInfoUpdate({
    rcId: route.query.id,
    accFileNames: fileList.value.map(v => v.fileName)
  })
    .then(() => {})
    .finally(() => {
      if (deleteFileList.value.length) {
        deleteFileList.value.forEach(async file => {
          await delFile(file.fileName)
        })
      }
      closeModal()
    })
}
function closeModal() {
  showModal.value = false
  deleteFileList.value = []
  if (fileList.value.length) {
    fileList.value = []
  }

  init()
}

function handleExceed() {
  proxy.$modal.msgError('最多只能上传3个文件')
}

init()
</script>

<style scoped lang="scss">
@import '@/assets/styles/detailsStyle.scss';

.details {
  // padding: 20px 0px 20px 15px;
  background-color: #f4f4f5;
  min-height: calc(100vh - 130px);
  .box-card {
    min-height: calc(100vh - 150px);
  }
  ::v-deep .details-left .el-card__body {
    padding: 15px 0px 20px 0px;
  }
  ::v-deep .el-checkbox-button__inner {
    width: 100%;
    text-align: center;
    background: #e7f3ff !important;
    color: #1890ff;
    border: 1px solid #8bc7ff;
  }
  .dropdown ::v-deep .el-dropdown {
    width: 100%;
  }
  .details-left-top {
    img {
      @include wh(80px, 80px);
      display: block;
      margin: 15px auto;
    }
    .top-img {
      border-radius: 12.5rem;
      background: #ff933c;
      @include wh(80px, 80px);
      margin: 10px auto;
      i {
        background-color: #fff;
        line-height: 80px;
        margin: 18px auto;
      }
    }
  }
  // 项目资产概括
  .xmzcgk {
    .el-col {
      margin-bottom: 15px;
      &:last-child {
        margin-bottom: 0px;
      }
    }
  }
}
</style>
